package controller;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;

import dao.NhasanxuatDAO;
import dao.NhomsanphamDAO;
import dao.SanphamDAO;
import dao.ThamsochungDAO;

import pojo.Sanpham;
import util.BeanUtil;
import util.ConvertHelper;

@ManagedBean(name = "trangSanPhamTheoNhaSanXuatBean")
@ViewScoped
public class TrangSanPhamTheoNhaSanXuatBean implements Serializable{

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	private List<Sanpham> lstSanPham = new ArrayList<Sanpham>();
	private String manhasanxuat = ((HeaderBean) BeanUtil
			.findBean("headerBean")).getManhasanxuat();
	
	public String GetTenNhaSanXuat()
	{
		return (new NhasanxuatDAO()).get(Integer.parseInt(manhasanxuat)).getTennhansanxuat().toUpperCase();
	}
	
	
	public TrangSanPhamTheoNhaSanXuatBean()
	{
		System.out.println("Khoi tao TrangSanPhamTheoNhaSanXuatBean ");
		LaySanPhamTheoNhaSanXuat();
	}
	
	public void LaySanPhamTheoNhaSanXuat()
	{	
		Map<String,String> params =  FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap();
		String thututrang = params.get("thututrang");
		
		int index = 1;
		if(thututrang != null)
			index = Integer.parseInt(thututrang);
		
		System.out.println("Thu tu trang trong LaySanPhamTheoNhom là : " + thututrang);
		int nSPTrenTrang = LaySoSPTrenTrang();	
		int FromIndex = nSPTrenTrang * (index - 1);
		
		SanphamDAO spDAO = new SanphamDAO();
		lstSanPham = spDAO.GetSanPhamTheoMaNhaSanXuat(Integer.parseInt(manhasanxuat), FromIndex, nSPTrenTrang);	
		
		//((HeaderBean) BeanUtil.findBean("headerBean")).setManhomsanpham("");
	}
	
	public int XacDinhSoTrang()
	{
		SanphamDAO spDAO = new SanphamDAO();
		int nSanPham = spDAO.CountSanPhamTheoMaNhaSanXuat(Integer.parseInt(manhasanxuat));
        int nSPTrenTrang = LaySoSPTrenTrang();
        int nTrang =  nSanPham / nSPTrenTrang;
        nTrang = nSanPham % nSPTrenTrang == 0 ? nTrang: nTrang + 1;
        
        return nTrang;      
	}
	
	private int LaySoSPTrenTrang()
	{
		ThamsochungDAO thamsochung = new ThamsochungDAO();
        return Integer.parseInt(thamsochung.LayGiaTriCuaThamSo(ThamsochungDAO.TenThamSo.SO_SAN_PHAM_TREN_TRANG).toString());
	}
	
	public List<Sanpham> getLstSanPham() {
		return lstSanPham;
	}
	
	public void setLstSanPham(List<Sanpham> lstSanPham) {
		this.lstSanPham = lstSanPham;
	}

}
